<template>
    <component
        :is="componentMap[curTab]"
        :isRegist="isRegist"
        :menuList="menuList"
        :applications="applications"
        :unreadMessageNum="unreadMessageNum"
        :currentUser="currentUser"
        :showManage="showManage"
        :showPersonCenter="showPersonCenter"
        :showStrain="showStrain"
        :brandInfo="brandInfo"
        @change-menu="changeMenu"
        :active-route="checkedRoute"
        :navTemplateId="navTemplateId"
        isSelfLoginFunc
        isSelfExitFunc
        @login="login"
        @exit="exit"
    ></component>
</template>

<script setup>
import HomeHeaderMenu from './part/home-header-menu.vue';

import {ref, computed, watch, onMounted} from 'vue';
import {pageJump} from '@/global/location-transfer';
import {useStore} from 'vuex';
import {useRoute} from 'vue-router';
import {routeStatic} from '@/router/routes-static.js';
import {XCMainHeader} from '@yanxiu/header';

const store = useStore();
const route = useRoute();

const props = defineProps({
    curTab: {
        // 菜单
        type: String,
        default: 'home'
    }
});

function login () {
    store.dispatch('logout');
}
 
 
function exit() {
    store.dispatch('logoutHome');
}

const componentMap = {
    home: HomeHeaderMenu, // 首页导航
    main: XCMainHeader // 二级页导航
};
//  ---------- 头部npm 包 配置
const applications = ref([]);
// 获取是否登录
const registMap = computed(() => {
    let pagePermission = store.state?.pagePermission || {};
    let list =
        pagePermission['accountManage:loginAndRegist:isOpen']?.moduleRuleList ||
        [];
    let temp = {};
    list?.length &&
        list.forEach(element => {
            temp[element.ruleKey] = element.checked;
        });
    return temp;
});

const isRegist = computed(() => {
    return !registMap.value?.['0'];
});
// 是否显示管理中心
const showManage = computed(() => {
    let pagePermission = store.state?.pagePermission || {};
    let isHaveIdmx = store.state.user?.isHaveIdmx;
    return !!pagePermission['manageCenter:base:home'] && isHaveIdmx;
});
// 是否显示个人中心
const showPersonCenter = computed(() => {
    let pagePermission = store.state?.pagePermission || {};
    return !!pagePermission['personalCenter:page'];
});
// 是否显示培训管理系统
const showStrain = computed(() => {
    let pagePermission = store.state?.pagePermission || {};
    let isHaveStrain = store.state.user?.isHaveStrain;
    console.log(
        !!pagePermission.continuingEducation &&
            !!pagePermission.train &&
            isHaveStrain
    );
    return (
        !!pagePermission.continuingEducation &&
        !!pagePermission.train &&
        isHaveStrain
    );
});
// 全部备案信息
const brand = computed(() => {
    // console.log('brand====', JSON.stringify(store.state.brand))
    return store.state.brand?.publishBrand || {};
});

// 具体备案信息
const brandInfo = computed(() => {
    // console.log('brandInfo====', JSON.stringify(brand.value?.brandConfig))
    return brand.value?.brandConfig || {};
});

// 获取用户当前信息

const currentUser = ref({});
const username = computed(() => {
    return currentUser.value?.realName || currentUser.value?.name || '';
});
const navTemplateId = computed(() => {
    return store.state.user?.navTemplateId || '';
});
// 监听个人信息变化
watch(
    () => store.state.currentUser,
    val => {
        currentUser.value = val;
        if (val.userId) {
            store.dispatch('user/getUnreadMessage');
            getApplicationList();
        }
    },
    {deep: true, immediate: true}
);

// 获取应用
function getApplicationList() {
    G_transmit('getUserCenterLatestBrand', {})
        .then(res => {
            const data = res?.data || [];
            let menuList = [];
            let tempMap = {};
            data.length &&
                data.forEach(item => {
                    if (
                        item.moduleKey &&
                        routeStatic[item.moduleKey] &&
                        routeStatic[item.moduleKey].name &&
                        !tempMap[item.moduleKey]
                    ) {
                        tempMap[item.moduleKey] = item;
                        let temp = {
                            path: routeStatic[item.moduleKey].path,
                            id: item.moduleKey,
                            title: routeStatic[item.moduleKey].title,
                            shortTitle: routeStatic[item.moduleKey].shortTitle,
                            route: {name: routeStatic[item.moduleKey].name},
                            isOther: false,
                            icon: images[item.moduleKey]
                        };
                        menuList.push(temp);
                    }
                });
            applications.value = menuList || [];
        })
        .catch(() => {});
}

onMounted(() => {
    getApplicationList();
});
const images = {
    'resourceApplication:my': require('@/assets/img/menu-icon/resource.png'),
    'coopgroup:my': require('@/assets/img/menu-icon/group.png'),
    'activity:my': require('@/assets/img/menu-icon/activity.png'),
    'train:my': require('@/assets/img/menu-icon/course.png'),
    'continuingEducation:my': require('@/assets/img/menu-icon/teach.png'),
    'video:my': require('@/assets/img/menu-icon/case.png'),
    'moocApplication:my': require('@/assets/img/menu-icon/mooc.png'),
    'material:my': require('@/assets/img/menu-icon/material.png'),
    'workshop:my': require('@/assets/img/menu-icon/studio.png') 
};

// 获取消息数量
const unreadMessageNum = computed(() => {
    let num =
        store.state?.unreadMessage?.like + store.state?.unreadMessage?.message;
    if (+num == 0) {
        num = false;
    }
    if (+num > 99) {
        num = '99+';
    }
    return num;
});

const menuList = computed(() => {
    let list = store.getters['user/userMenus'] || [];
    return list.filter(item => {
        return item?.path || (item?.sub_navs && item?.sub_navs.length);
    });
});

// 高亮路由
const activePath = computed(() => {
    return route.path;
});

// 高亮路由
const checkedRoute = computed(() => {
    const curRoute =
        menuList.value.find(item => {
            if (getActive(item)) {
                return true;
            }
            return false;
        }) || {};
    return curRoute;
});

// 一级导航选中状态
function getActive(menuItem) {
    if (menuItem?.path && menuItem.path.indexOf(activePath.value) > -1) {
        return true;
    }
    if (menuItem?.sub_navs && menuItem?.sub_navs.length) {
        //
        let curItem = menuItem?.sub_navs?.find(subItem => {
            return (
                subItem?.path && subItem?.path.indexOf(activePath.value) > -1
            );
        });
        return !!curItem;
    }
    return false;
}

// 点击导航
function changeMenu(menuItem) {
    if (menuItem?.sub_navs && menuItem?.sub_navs.length) {
        return;
    }
    pageJump(menuItem);
}
</script>

<style lang="scss" scoped></style>
